using System.Diagnostics;

namespace Rabbit3.Api.Middleware
{
    /// <summary>
    /// 性能监控中间件
    /// </summary>
    public class PerformanceMonitoringMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<PerformanceMonitoringMiddleware> _logger;

        public PerformanceMonitoringMiddleware(RequestDelegate next, ILogger<PerformanceMonitoringMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            
            // 在响应开始前添加响应头
            context.Response.OnStarting(() =>
            {
                var elapsedMs = stopwatch.ElapsedMilliseconds;
                context.Response.Headers["X-Response-Time"] = $"{elapsedMs}ms";
                return Task.CompletedTask;
            });
            
            try
            {
                await _next(context);
            }
            finally
            {
                stopwatch.Stop();
                
                var elapsedMs = stopwatch.ElapsedMilliseconds;
                var method = context.Request.Method;
                var path = context.Request.Path;
                var statusCode = context.Response.StatusCode;
                
                // 记录慢查询（超过1秒的请求）
                if (elapsedMs > 1000)
                {
                    _logger.LogWarning("慢请求检测: {Method} {Path} - {StatusCode} - {ElapsedMs}ms", 
                        method, path, statusCode, elapsedMs);
                }
                else if (elapsedMs > 500)
                {
                    _logger.LogInformation("请求性能: {Method} {Path} - {StatusCode} - {ElapsedMs}ms", 
                        method, path, statusCode, elapsedMs);
                }
            }
        }
    }

    /// <summary>
    /// 性能监控中间件扩展
    /// </summary>
    public static class PerformanceMonitoringMiddlewareExtensions
    {
        public static IApplicationBuilder UsePerformanceMonitoring(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<PerformanceMonitoringMiddleware>();
        }
    }
}
